import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'sqlite_util.dart';

class MainManager with ChangeNotifier {
  static MainManager instance = MainManager();

  List allFavorite = [];
  final sqliteUtil = SqliteUtil();

  void init() async {
    sqliteUtil.createDb(1);
    // clearDb();
    refreshDbList();
  }

  Future queryAll() async {
    return query("select * from zhongyaoFavorite");
  }

  void clearDb() {
    sqliteUtil.delete("DELETE FROM zhongyaoFavorite");
  }

  Future query(sql) async {
    return sqliteUtil.query(sql);
  }

  bool isLike(info) {
    return !allFavorite.every((item) {
      return (item['id'].toString() != info['id'].toString());
    });
  }

  void like(info) async {
    if (!isLike(info)) {
      allFavorite.add(info);
    } else {
      allFavorite.removeWhere((item) {
        return item['id'].toString() == info['id'].toString();
      });
    }

    update(allFavorite);
  }

  void insert(info) async {
    var data = json.encode(info);
    await sqliteUtil
        .insert('INSERT INTO zhongyaoFavorite(id,info) VALUES(0,"$data")');
    refreshDbList();
  }

  void update(info) async {
    await sqliteUtil.update('UPDATE zhongyaoFavorite SET info = ? WHERE id = 0',
        [json.encode(info)]);
    refreshDbList();
  }

  void delete(info) async {
    await sqliteUtil
        .delete('DELETE FROM zhongyaoFavorite WHERE id = ${info['id']}');
    refreshDbList();
  }

  refreshDbList() {
    queryAll().then((res) {
      if (res.length == 0) {
        allFavorite = [];
        insert(allFavorite);
        notifyListeners();
      } else {
        allFavorite = json.decode(res[0]['info']);
        notifyListeners();
      }
      // print(allFavorite);
    });
  }
}
